package com.ourway.entity.filter;

import cn.hutool.json.JSONUtil;
import com.liuweiheng.base.constant.redis.GlobalStrRedisConstant;
import com.liuweiheng.base.entity.R;
import com.liuweiheng.base.utils.GlobalStrRedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 *
 * @author lwh
 * @date 2021/11/27
 */
@WebFilter(urlPatterns = {"/feishu/v/*", "/feishu/**/v"}, filterName = "TokenFilter")
@Slf4j
public class TokenFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;

        String token = req.getHeader("X-Token");

        boolean verifyFlag = false;

        if (null != token && !token.isEmpty()) {
            // 校验token
            String key = GlobalStrRedisConstant.USER_LOGIN_TOKEN + "_" + token;
            verifyFlag = GlobalStrRedisUtil.hasKey(key);
        }

        if (verifyFlag) {
            req.setAttribute("X-Token", token);
            filterChain.doFilter(req, rep);
        } else {
            try (OutputStreamWriter osw = new OutputStreamWriter(rep.getOutputStream(), StandardCharsets.UTF_8); PrintWriter writer = new PrintWriter(osw, true)) {
                String jsonStr = JSONUtil.toJsonStr(R.error("用户授权失败"));
                writer.write(jsonStr);
                writer.flush();
                writer.close();
                osw.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }

    }

    @Override
    public void destroy() {

    }
}
